#include <iostream>
#include <unistd.h>
#include <cerrno>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;

int main()
{
    //1.创建管道
    int pipefd[2] = {0};

    int n = pipe(pipefd);
    if(n < 0)
    {
        //失败，-1被返回
        cout << "error :" << errno << strerror(errno) << endl;
    }
    //cout << "00000000000000000000000000000" << endl;

    //2.创建子进程
    pid_t id = fork();
    if(id == -1)
    {
        //创建子进程失败
        perror("fork filed::");
        exit(-1);
    }

    if(id == 0)
    {
        //child process
        //子进程进行读取,关闭写端
        close(pipefd[1]);

        char buff[1024];
        int n = read(pipefd[0] ,buff, sizeof(buff)-1);
        if(n > 0)
        {
            buff[n] = '\0';
            cout << buff << endl;
        }

        exit(1);
    }

    //父进程进行写入,关闭读端
    close(pipefd[0]);
    char buff[1024];
    string str = "i am father";
    snprintf(buff, sizeof(buff), "%s\n", str.c_str());
    //向管道中写入
    write(pipefd[1], buff, strlen(buff));
    
    
    //回收子进程
    int status = 0;
    int ret = waitpid(id, &status, 0);
    if(ret == -1)
    {
         printf("i an parent, child:%d, exit signal:%d, exit code:%d, coredump:%d\n", 
                    ret, status&0x7F, WEXITSTATUS(status), (status>>7)&1);
    }

    return 0;
}